Introduction to Methods and Code Reusability in Java
Course: Core Java Training
Topic: Introduction to Methods and Code Reusability
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Academy Website: JustAcademy Official Website
1. Introduction to Methods in Java
A method in Java is a named block of code designed to perform a particular task. Methods help organize a program into smaller, manageable sections that can be called whenever their functionality is needed.
For example, a program may need to calculate a total price, display a welcome message, check whether a number is even, or calculate a student's grade. Instead of writing the same logic repeatedly, a developer can define a method for each operation and call it whenever necessary.
Methods are fundamental to Java programming because they improve code organization, readability, maintainability, testing, and code reuse.
Learning Objectives
- Understand the meaning and purpose of methods in Java.
- Learn the syntax for declaring and calling methods.
- Identify method names, parameters, return types, and method bodies.
- Understand the difference between parameters and arguments.
- Learn methods with and without return values.
- Understand static and instance methods.
- Apply code reusability to real-world programming problems.
- Learn method naming conventions and best practices.
2. What Is a Method?
A method is a reusable unit of code declared inside a class or interface. It can accept input values through parameters, execute statements, and optionally return a result to the code that called it.
A method normally executes when it is invoked. The special main() method serves as the standard entry point for a traditional Java application launched by the Java Virtual Machine.
Example: A Simple Method
public class MethodExample {
static void greet() {
System.out.println("Welcome to Core Java!");
}
public static void main(String[] args) {
greet();
}
}
Output:
Welcome to Core Java!
Explanation:
MethodExample is the class name.
greet() is a user-defined method.
static allows the method to be called from the class without creating an object.
void indicates that the method does not return a value.
System.out.println() displays the welcome message.
- The statement
greet(); invokes the method.
3. Why Are Methods Important?
Methods help developers break large programs into smaller operations. Each method can handle one specific responsibility, making the complete application easier to understand and maintain.
| Benefit |
Explanation |
| Code reusability |
Write the logic once and call it from multiple places. |
| Readability |
Meaningful method names explain what an operation does. |
| Maintainability |
Update logic in one method instead of changing several duplicated sections. |
| Modularity |
Divide a large problem into smaller tasks. |
| Testing |
Methods with clear inputs and outputs can be tested independently. |
| Debugging |
Smaller units make it easier to isolate problems. |
| Abstraction |
Callers can use a method without needing to know every implementation detail. |
| Collaboration |
Different developers can work on separate methods or classes with clearly defined responsibilities. |
4. Understanding Code Reusability
Code reusability means using an existing implementation again rather than writing the same logic from scratch. In Java, methods are one of the simplest and most important ways to achieve this.
Without Code Reusability
public class RepeatedCodeExample {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
}
}
This program repeats the same output statement three times. If the message needs to change, each repeated statement may need to be updated.
With Code Reusability
public class ReusableCodeExample {
static void displayWelcomeMessage() {
System.out.println("Welcome to Java!");
}
public static void main(String[] args) {
displayWelcomeMessage();
displayWelcomeMessage();
displayWelcomeMessage();
}
}
Output:
Welcome to Java!
Welcome to Java!
Welcome to Java!
In this version, the message is defined in one place. Every invocation reuses the same method implementation.
Important Point
Code reusability does not mean every repeated statement must become a separate method. A method is most useful when it represents a meaningful task that can be named, reused, tested, or maintained independently.
5. Syntax of a Method in Java
The general syntax of a Java method is:
accessModifier staticOrInstance returnType methodName(parameters) {
// Method body
// Statements to perform a task
return value; // Required when a value must be returned
}
The modifiers and parameters vary depending on the method's purpose. The method body contains the statements that perform the operation.
Parts of a Method
| Component |
Description |
Example |
| Access modifier |
Controls where the method can be accessed. |
public, private |
| static |
Declares a class-level method rather than an instance method. |
static |
| Return type |
Specifies the type of value returned, or void if there is no returned value. |
int, String, void |
| Method name |
Identifies the method and is used when invoking it. |
calculateTotal |
| Parameters |
Declare the inputs accepted by the method. |
int a, int b |
| Method body |
Contains statements that implement the operation. |
{ return a + b; } |
| Return statement |
Sends a result back to the caller when the method has a non-void return type. |
return a + b; |
6. Declaring and Calling a Method
Declaring a method means defining its name, return type, parameters, and implementation. Calling or invoking a method means requesting that the method execute.
Example
public class DisplayExample {
static void displayMessage() {
System.out.println("Methods make code reusable.");
}
public static void main(String[] args) {
displayMessage();
displayMessage();
}
}
Output:
Methods make code reusable.
Methods make code reusable.
The method is declared once but invoked twice. Each invocation executes the statements inside the method body.
Important Rules
- Methods are declared inside a class or interface, not directly inside another ordinary method.
- A method name must follow Java identifier rules and cannot be a reserved keyword.
- Method calls use parentheses, even when no arguments are required.
- A non-void method must return a compatible value on every execution path that completes normally.
- A void method does not return a value, although it can use a bare
return; to exit early.
7. Types of Methods in Java
Methods can be classified in different ways depending on whether they are predefined or user-defined, whether they are static or instance methods, and whether they accept parameters or return values.
7.1 Predefined Methods
Predefined methods are supplied by Java's standard libraries and classes. Developers can call them instead of implementing the same functionality themselves.
public class PredefinedMethodExample {
public static void main(String[] args) {
String name = "java";
System.out.println(name.toUpperCase());
System.out.println(Math.max(10, 25));
}
}
Output:
JAVA
25
toUpperCase() is an instance method of String, while Math.max() is a static method.
7.2 User-Defined Methods
User-defined methods are written by programmers to meet an application's requirements.
public class UserDefinedMethodExample {
static int square(int number) {
return number * number;
}
public static void main(String[] args) {
System.out.println(square(5));
}
}
Output:
25
7.3 Static Methods
A static method belongs to the class rather than to a particular object. It can be called through the class name and cannot directly access instance fields or instance methods without an object reference.
public class Calculator {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = Calculator.add(10, 20);
System.out.println(result);
}
}
Output:
30
7.4 Instance Methods
An instance method belongs to an object. It can work with the object's instance fields and other accessible instance methods.
public class Student {
String name;
Student(String name) {
this.name = name;
}
void displayName() {
System.out.println("Student: " + name);
}
public static void main(String[] args) {
Student student = new Student("Aarav");
student.displayName();
}
}
Output:
Student: Aarav
Here, displayName() reads the name belonging to the particular Student object.
8. Methods Without Parameters
A method does not need parameters if it can perform its task without receiving input from the caller.
Example
public class NoParameterExample {
static void showCourse() {
System.out.println("Core Java Training");
}
public static void main(String[] args) {
showCourse();
}
}
Output:
Core Java Training
The empty parentheses in showCourse() indicate that the method accepts no parameters.
9. Methods With Parameters
Parameters allow methods to receive input values. They make a method more reusable because the same logic can operate on different data each time it is called.
Example: Greeting Different Users
public class GreetingExample {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Asha");
greet("Rahul");
greet("Neha");
}
}
Output:
Hello, Asha!
Hello, Rahul!
Hello, Neha!
The method is written once and accepts a different name for each invocation.
Methods With Multiple Parameters
public class AdditionExample {
static void addNumbers(int a, int b) {
int sum = a + b;
System.out.println("Sum: " + sum);
}
public static void main(String[] args) {
addNumbers(10, 20);
addNumbers(100, 200);
}
}
Output:
Sum: 30
Sum: 300
Each parameter declaration includes a data type and a variable name. Multiple parameters are separated by commas.
10. Difference Between Parameters and Arguments
Parameters are variables declared in a method definition. Arguments are the actual values or expressions supplied when the method is called.
static int multiply(int number, int factor) {
return number * factor;
}
public static void main(String[] args) {
int result = multiply(5, 4);
System.out.println(result);
}
Output:
20
| Term |
Meaning |
Example |
| Parameter |
Variable declared in the method definition. |
int number, int factor |
| Argument |
Value supplied in the method call. |
5, 4 |
11. Methods With Return Values
A method can calculate or retrieve a result and return it to the caller. Its return type specifies the kind of value it can return.
Example: Returning a Sum
public class ReturnExample {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(15, 25);
System.out.println("Result: " + result);
}
}
Output:
Result: 40
The expression a + b is evaluated, and the resulting integer is returned to the caller. The caller stores the returned value in the result variable.
Returning Different Data Types
static double calculateArea(double length, double width) {
return length * width;
}
static String getCourseName() {
return "Core Java";
}
static boolean isAdult(int age) {
return age >= 18;
}
These methods return a double, a String, and a boolean, respectively. A method's declared return type must be compatible with its returned value.
12. Void Methods and Value-Returning Methods
| Feature |
Void Method |
Value-Returning Method |
| Return type |
void |
A type such as int, double, or String |
| Purpose |
Performs an operation without returning a value. |
Computes or retrieves a value for the caller. |
| Return statement |
May use return; for early exit. |
Must return a compatible value on all normal completion paths. |
| Example |
static void greet() |
static int square(int n) |
Example of Both Types
public class MethodTypesExample {
static void displayMessage() {
System.out.println("Learning Java methods");
}
static int getNumber() {
return 100;
}
public static void main(String[] args) {
displayMessage();
int number = getNumber();
System.out.println(number);
}
}
Output:
Learning Java methods
100
13. How the return Statement Works
The return statement ends the current method execution and, for a non-void method, sends a value back to the caller.
Example
public class ReturnStatementExample {
static int getLargerNumber(int a, int b) {
if (a > b) {
return a;
}
return b;
}
public static void main(String[] args) {
System.out.println(getLargerNumber(40, 25));
}
}
Output:
40
When a is greater than b, the first return statement ends the method. Otherwise, the second return statement returns b.
14. Code Reusability Through Methods: A Practical Example
Suppose a shopping application needs to calculate the final price of several products after applying the same tax rate. A reusable method can keep the calculation in one place.
Example: Calculating Prices
public class ShoppingCalculator {
static double calculateFinalPrice(double price, double taxRate) {
return price + (price * taxRate / 100);
}
public static void main(String[] args) {
double firstPrice = calculateFinalPrice(1000, 18);
double secondPrice = calculateFinalPrice(500, 18);
double thirdPrice = calculateFinalPrice(200, 5);
System.out.println("First Product: " + firstPrice);
System.out.println("Second Product: " + secondPrice);
System.out.println("Third Product: " + thirdPrice);
}
}
Output:
First Product: 1180.0
Second Product: 590.0
Third Product: 210.0
The calculation is defined only once. Different prices and tax rates can be supplied as arguments, avoiding duplicated calculation logic.
Real-world applications: price calculations, payroll processing, student grading, validation, report generation, data conversion, and repeated business rules.
15. Breaking Large Problems Into Smaller Methods
Breaking a large problem into smaller, focused methods is called functional decomposition. Each method handles a particular responsibility, and the main workflow coordinates those methods.
Example: Student Result Processing
public class StudentResult {
static int calculateTotal(int mark1, int mark2, int mark3) {
return mark1 + mark2 + mark3;
}
static double calculatePercentage(int total) {
return total / 3.0;
}
static void displayResult(String name, double percentage) {
System.out.println("Student: " + name);
System.out.println("Percentage: " + percentage + "%");
}
public static void main(String[] args) {
int total = calculateTotal(80, 90, 85);
double percentage = calculatePercentage(total);
displayResult("Riya", percentage);
}
}
Output:
Student: Riya
Percentage: 85.0%
This program separates calculation from presentation. The total and percentage calculations can be reused in other parts of the application without duplicating their implementation.
16. Method Overloading: Reusing a Method Name
Method overloading allows a class to define multiple methods with the same name but different parameter lists. The compiler selects an applicable overload based on the arguments supplied.
Example
public class OverloadingExample {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(10, 20));
System.out.println(add(10, 20, 30));
System.out.println(add(2.5, 3.5));
}
}
Output:
30
60
6.0
The methods share the name add, but their parameter lists differ.
Important Rules for Overloading
- Overloaded methods must have different parameter lists, such as different parameter types, counts, or applicable parameter arrangements.
- Changing only the return type is not enough to overload a method.
- Overloading is resolved at compile time using the method name and applicable arguments.
- Use overloading when the methods represent closely related operations.
17. Method Parameters and Java's Pass-by-Value Behavior
Java passes arguments by value. For primitive parameters, the method receives a copy of the primitive value. For object parameters, the method receives a copy of the reference value, which can still refer to the same object.
Primitive Example
public class PassByValueExample {
static void changeNumber(int number) {
number = 100;
}
public static void main(String[] args) {
int value = 10;
changeNumber(value);
System.out.println(value);
}
}
Output:
10
The method changes its local parameter, not the caller's variable.
Object Reference Example
public class ObjectParameterExample {
static void updateName(StringBuilder text) {
text.append(" Java");
}
public static void main(String[] args) {
StringBuilder message = new StringBuilder("Core");
updateName(message);
System.out.println(message);
}
}
Output:
Core Java
The copied reference points to the same StringBuilder object, so the method can modify that object's contents. Java still passes the reference by value; it does not pass objects by reference.
18. Method Scope and Local Variables
A local variable is declared inside a method or block and is available only within its scope. A parameter is also local to the method in which it is declared.
public class LocalVariableExample {
static void displayNumber() {
int number = 50;
System.out.println(number);
}
public static void main(String[] args) {
displayNumber();
}
}
Output:
50
The variable number cannot be accessed directly from outside the method. Its lifetime and scope are tied to the method execution and its block.
19. Common Mistakes When Working With Methods
| Mistake |
Why It Is a Problem |
How to Fix It |
| Forgetting parentheses when calling a method |
A method invocation requires parentheses. |
Write displayMessage();. |
| Using the wrong number of arguments |
The call may not match any applicable method. |
Check the declared parameter list. |
| Using incompatible argument types |
The compiler may reject the call. |
Pass compatible values or use a suitable overload. |
| Forgetting a required return value |
A non-void method may fail to compile if a normal execution path returns no value. |
Return an appropriate value on every required path. |
| Returning the wrong data type |
The returned expression may not be compatible with the declared return type. |
Match the returned value to the method's return type. |
| Calling an instance method directly from static context |
An instance method requires an object. |
Create an object or redesign the method appropriately. |
| Duplicating large blocks of logic |
Updates become harder and errors can appear in different copies. |
Extract a focused reusable method. |
| Creating methods that do too many things |
Complex methods are harder to test and maintain. |
Split unrelated responsibilities into smaller methods. |
20. Best Practices for Writing Reusable Methods
- Choose meaningful names such as
calculateTotal(), validateEmail(), and displayReport().
- Follow Java's camelCase convention for method names.
- Give each method one clear, focused responsibility.
- Use parameters to provide the input that varies between calls.
- Return results when callers need to use the calculated values.
- Use
void when the method performs an operation without returning a result.
- Keep methods short enough to understand without excessive scrolling, while avoiding unnecessary fragmentation.
- Use suitable access modifiers such as
private for implementation details that do not need to be exposed.
- Validate inputs when invalid values could produce incorrect results.
- Avoid unexpected side effects and document important side effects or exceptions.
- Test methods using normal inputs, boundary values, and invalid inputs where appropriate.
- Do not duplicate the same business rule across several methods when a shared implementation is more appropriate.
21. Practice Exercises
- Write a method named
displayWelcome() that prints a welcome message.
- Create a method that accepts two integers and prints their sum.
- Write a method that returns the square of an integer.
- Create a method that determines whether a number is even or odd.
- Write a method that accepts a name and returns a greeting message.
- Create a method that calculates the area of a rectangle using length and width parameters.
- Write an overloaded method named
multiply() for two integers and three integers.
- Create a method that accepts three marks and returns their average.
- Write a reusable method that calculates the final price after applying a discount percentage.
- Build a simple calculator using separate methods for addition, subtraction, multiplication, and division.
- Create a student result program with separate methods for calculating total, percentage, and displaying the result.
- Write a program that demonstrates the difference between a static method and an instance method.
22. Interview Questions and Answers
Q1. What is a method in Java?
A method is a named block of code that performs a particular task and can be invoked when required.
Q2. Why are methods used in Java?
Methods support code reuse, modularity, readability, maintainability, testing, and separation of responsibilities.
Q3. What is code reusability?
Code reusability means using an existing implementation in multiple places rather than duplicating the same logic.
Q4. What is the difference between method declaration and method invocation?
Declaration defines the method's characteristics and implementation. Invocation calls the method to execute it.
Q5. What is the difference between parameters and arguments?
Parameters are variables declared in the method definition. Arguments are values supplied when the method is called.
Q6. What is a return type?
A return type specifies the kind of value a method can return. A method that returns no value uses the void return type.
Q7. Can a void method use a return statement?
Yes. A void method can use a bare return; to exit early, but it cannot return a value.
Q8. What is a static method?
A static method belongs to the class and can be called without creating an instance of that class.
Q9. What is an instance method?
An instance method belongs to an object and can operate on that object's instance data.
Q10. What is method overloading?
Method overloading means defining multiple methods with the same name but different parameter lists.
Q11. Can methods be overloaded by changing only the return type?
No. The parameter list must differ in a way that makes the method declarations distinct. Changing only the return type is insufficient.
Q12. What happens when a method is called?
Program execution transfers to the method body, its statements execute, and control returns to the caller when the method finishes or returns.
Q13. What is functional decomposition?
Functional decomposition is the process of dividing a larger problem into smaller, focused operations, often implemented as separate methods.
Q14. Does Java pass arguments by reference?
No. Java always passes arguments by value. For object arguments, the copied value is a reference to the object.
Q15. What makes a method reusable?
A method is more reusable when it has a clear responsibility, meaningful inputs, predictable behavior, and an appropriate result or documented effect.
23. Quick Revision Checklist
- A method is a named unit of code that performs a task.
- Methods are declared inside classes or interfaces.
- Methods are invoked using their names and parentheses.
- Parameters receive input values from arguments.
- A return type specifies the result type, or
void when no value is returned.
- Static methods belong to the class; instance methods belong to objects.
- Method overloading allows the same name with different parameter lists.
- Code reusability reduces duplicated logic and simplifies maintenance.
- Focused methods help make programs modular and testable.
- Java passes all arguments by value.
24. Conclusion
Methods are essential building blocks of Core Java programming. They allow developers to organize instructions into named operations, accept input through parameters, return results, and reuse logic across an application.
By using focused methods and avoiding unnecessary duplication, developers can create programs that are easier to read, test, debug, and maintain. Understanding method declarations, invocations, parameters, return types, static and instance methods, and method overloading provides a strong foundation for learning object-oriented programming and advanced Java concepts.
25. Further Learning Resources